import type { SocketClient } from "@/plugins/websocket";
import { defineStore } from "pinia";
import { inject, provide } from "vue";

export const useChatMessageStore = defineStore("chat-message", {
  // 开启数据缓存
  // persist: {
  //   enabled: false,
  // },
  state: () => {
    return {
      data: <any>{},
      socket: <SocketClient>inject('socket')!,
      // client: null as unknown as SocketClient
    };
  },
  getters: {

    listMessage(userId: any) {
      return this.data[userId] || []
    }
    
  },
  actions: {

    async connect(userId: any) {
      this.socket.connect({
        url: `/${userId.value}`,
      });
      // .then(() => {
      provide("socket-client", this.socket);
      // this.client = this.socket
    },
    // 加载用户的聊天记录
    async init(userId: any) {
      const key = `chat.message.${userId}`
      this.data = JSON.parse(localStorage.getItem(key) || '{}')

      await this.connect(userId)
      
      // 监听消息接收
      // this.client.on('message', (msg: any) => {
      //   const fromId = msg.from
      //   this.data[fromId].push(msg)
      // })

    },

    send(message: any) {
      const id = message.to
      this.socket.send(message)
      if (this.data[id]) {
        this.data[id].push(message)
      } else {
        this.data[id] = [message]
      }
    },

    listenerMessage(callback: (message: any) => void = () => {}) {
      console.log(this.client);
      
      this.socket.on('message', (msg: any) => {
        const fromId = msg.from
        this.data[fromId] = this.data[fromId]? this.data[fromId].push(msg) : [msg]
        callback(msg)
      })
    },

    // 获取聊天记录
    getMessage(userId: any) {
      if (this.data.hasOwnProperty(userId)) {
        return this.data[userId]
      } else {
        this.data = []
      }
    },

    setMessage(userId: any, message: any) {
      if (this.data.hasOwnProperty(userId)) {
        this.data[userId].push(message)
      } else {
        this.data = [message]
      }
    }
  }
});
